package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosOfferInstVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ExtOrderInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteInstChange;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import edu.emory.mathcs.backport.java.util.Collections;

@Service
public class KitePosAccountHandler implements IKitePosSceneHandler {

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private ICustReceptionService custReceptionService;

    @Override
    public void handle(KitePosHandlerContext context) {
        List<KitePosAccountDTO> accounts = new ArrayList<KitePosAccountDTO>();
        List<KiteOfferInst> offerInsts = Lists.newArrayList();
        Map<String, Object> custMap = new HashMap<>();
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);

        Map<String, KitePosOfferInstVO> mainOfferInstMap = context.getPosSceneBO().getMainOfferInstMap();
        Map<String, KitePosOfferInstVO> giftOfferInstMap = context.getPosSceneBO().getGiftOfferInstMap();
        if (!KiteMapUtils.isEmpty(giftOfferInstMap)) {
            Iterator<KitePosOfferInstVO> iterator = giftOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //融合商品实例
                offerInsts.add(offerInstVO.getOfferInst()); //融合商品实例
            }
        }
        else {
            Iterator<KitePosOfferInstVO> iterator = mainOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //套餐实例
                offerInsts.add(offerInstVO.getOfferInst()); //套餐实例
            }
        }

        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        String custId = KiteStringUtils.isNotEmpty(sceneInst.getCustId()) ? sceneInst.getCustId() : context.getCustId();
        if (KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)) {
            context.getPosDto().setAccounts(accounts);
            return;
        }
        // 获取分类
        String cateId = CuccPosServiceUtils.getCateId(context.getSceneInstId(), custId);
        String createDateStr = KiteDateUtils.formatDate(sceneInst.getCreateDate(), KiteDateUtils.DATE_TIME_FORMAT_14);

        offerInsts.forEach(offerInst -> {
            if (BatchAcceptUtil.isBatchSign(context.getSceneInstId())
                && KiteStringUtils.isNotEmpty(context.getOfferInstId())
                && !KiteStringUtils.equals(offerInst.getOfferInstId(), context.getOfferInstId())) {
                return;
            }
            List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService
                .listOfferInstAccts(custId, offerInst.getOfferInstId());
            if (Objects.isNull(offerInstAcctRels)) {
                //ErrorConsts.BUSI_CHECK_ERROR.throwOut("付费关系不能为空");
                offerInstAcctRels = new ArrayList<>();
            }
            offerInstAcctRels = offerInstAcctRels.stream().filter(acct -> !KiteStringUtils.equals(acct.getActionType().name(), ActionType.X.name())).collect(Collectors.toList());
            List<String> accountId = new ArrayList<>();
            KitePosDTO kitePosDTO = ExtOrderInfoCache.get(context.getSceneInstId());

            offerInstAcctRels.forEach((offerInstAcctRel) -> {
                if (!accountId.contains(offerInstAcctRel.getAcctId())) {
                    accountId.add(offerInstAcctRel.getAcctId());
                    String bssId = "";
                    String cBssId = "";
                    KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
                    if (!KiteObjectUtils.isEmpty(kitePosDTO) && !ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
                        String accountCustId = offerInstAcctRel.getCustId();
                        if (KiteStringUtils.equals(custId, accountCustId)) {
                            bssId = context.getCustDto().getCustId();
                            cBssId = context.getCustDto().getProvinceCustId();
                        }
                        else {
                            CuccCustInfoDetailDTO custInfoDetailDTO = getCust(accountCustId, custMap);
                            if (Objects.nonNull(custInfoDetailDTO)) {
                                bssId = custInfoDetailDTO.getCustId();
                                cBssId = custInfoDetailDTO.getProvinceCustId();
                            }
                        }
                        //ProvinceCustId不返回时 cbssid传空字符串下去
                        if(Objects.isNull(cBssId)){
                            cBssId = "";
                        }
                    }
                    KitePosAccountDTO account = new KitePosAccountDTO();
                    account.setInstanceId(offerInstAcctRel.getInstId());
                    if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(kiteSceneInst.getServiceOfferId())&&!LocalServiceOfferConsts.SERVICE_OFFER_ORDER_OPPER.equals(kiteSceneInst.getServiceOfferId())) {
                    	account.setInstanceId(CommonUtil.getInstanceId(LocalKeyConsts.ZH_INST_CODE, offerInstAcctRel.getInstId()));
                    }
                    account.setAccountId(offerInstAcctRel.getAcctId());
                    account.setName(offerInstAcctRel.getAcctName());
                    account.setPayMode(offerInstAcctRel.getPayModeCode()); //账户类型
                    account.setProvinceCode(offerInstAcctRel.getProvinceCode()); //省份-广东
                    account.setEparchyCode(offerInstAcctRel.getEparchyCode()); //地市
                    account.setIsGroupAccount(offerInstAcctRel.getIsDefault());
                    account.setCustId(offerInstAcctRel.getCustId());
                    account.setChangeType(ChangeTypeUtils.getChangeType(offerInstAcctRel.getActionType().name()));
                    //account.setOpenDate(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
                    if (!ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
                        account.setBssId(bssId);
                        account.setCbssId(cBssId);
                    }
                    else {
                        // 从缓存里面取
                        String sceneInstId = context.getSceneInstId();
                        List<InstAttrDTO> attrConfigs = queryScenePersonService
                            .listKiteConfigAttrs(sceneInstId, LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE).getResultObject().stream()
                            .filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType()))
                            .collect(Collectors.toList());
                        Map<String, String> orderAttrMap = new HashMap<String, String>();
                        attrConfigs.forEach(orderAttr -> orderAttrMap.put(orderAttr.getFieldName(), orderAttr.getValue()));
                        account.setBssId(orderAttrMap.get("provinceAcctId"));
                        account.setCbssId(orderAttrMap.get("cbssAcctId"));
                        String isDefault = orderAttrMap.get("is_trans_acct");
                        account.setChangeType(ChangeTypeUtils.getChangeType(offerInstAcctRel.getActionType().name()));

                        if (KiteStringUtils.isEqual(isDefault, "1")) {
                            account.setCustId("");
                        }
                        // 2021-12-22版本，过户，取消将默认账户转到新客户下的逻辑
                        /*else {
                            Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
                            Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
                            CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ?
                                (CuccCustInfoDTO) newCust :
                                context.getNewCustDto();
                            account.setCustId(newCustDto.getCustId());
                        }*/
                        account.setIsCenterDirectSign("0");
                        account.setAcctContractCode(orderAttrMap.get("acctContractCode"));
                    }
                    if (KiteStringUtils.isEqual(offerInstAcctRel.getActionType().name(), ActionType.M.name())) {
                        account.setChangeType("9");
                    }
                    if (KiteStringUtils.equalsAny(cateId, "2000998", "2100982", "2100983")) {
                        if (Objects.isNull(account.getAttrs())) {
                            account.setAttrs(Lists.newArrayList());
                        }
                        // 所属银行
                        List<KitePosAttrDTO> belBankAttr = account.getAttrs().stream().filter(attr -> KiteStringUtils.equals("OPEN_BANK", attr.getCode())).collect(Collectors.toList());
                        if (KiteListUtils.isEmpty(belBankAttr)) {
                            KitePosAttrDTO belBank = new KitePosAttrDTO();
                            belBank.setCode("OPEN_BANK");
                            belBank.setValue(Optional.ofNullable(offerInstAcctRel.getBelBank()).orElse(""));
                            belBank.setStartDate(createDateStr);
                            belBank.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                            account.getAttrs().add(belBank);
                        }
                        // 开户银行
                        List<KitePosAttrDTO> openAccountBankAttr = account.getAttrs().stream().filter(attr -> KiteStringUtils.equals("OPEN_ACCOUNT_BANK", attr.getCode())).collect(Collectors.toList());
                        if (KiteListUtils.isEmpty(openAccountBankAttr)) {
                            KitePosAttrDTO openAccountBank = new KitePosAttrDTO();
                            openAccountBank.setCode("OPEN_ACCOUNT_BANK");
                            openAccountBank.setValue(Optional.ofNullable(offerInstAcctRel.getOpenAccountBank()).orElse(""));
                            openAccountBank.setStartDate(createDateStr);
                            openAccountBank.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                            account.getAttrs().add(openAccountBank);
                        }
                        // 开户名称
                        List<KitePosAttrDTO> bankAccountNameAttr = account.getAttrs().stream().filter(attr -> KiteStringUtils.equals("BANK_ACCOUNT_NAME", attr.getCode())).collect(Collectors.toList());
                        if (KiteListUtils.isEmpty(bankAccountNameAttr)) {
                            KitePosAttrDTO bankAccountName = new KitePosAttrDTO();
                            bankAccountName.setCode("BANK_ACCOUNT_NAME");
                            bankAccountName.setValue(Optional.ofNullable(offerInstAcctRel.getBankAccountName()).orElse(""));
                            bankAccountName.setStartDate(createDateStr);
                            bankAccountName.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                            account.getAttrs().add(bankAccountName);
                        }
                        // 所属银行
                        List<KitePosAttrDTO> bankAccountNoAttr = account.getAttrs().stream().filter(attr -> KiteStringUtils.equals("BANK_ACOUNT_NO", attr.getCode())).collect(Collectors.toList());
                        if (KiteListUtils.isEmpty(bankAccountNoAttr)) {
                            KitePosAttrDTO bankAccountNo = new KitePosAttrDTO();
                            bankAccountNo.setCode("BANK_ACOUNT_NO");
                            bankAccountNo.setValue(Optional.ofNullable(offerInstAcctRel.getBankAccountNo()).orElse(""));
                            bankAccountNo.setStartDate(createDateStr);
                            bankAccountNo.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                            account.getAttrs().add(bankAccountNo);
                        }
                    }
                    accounts.add(account);
                }
            });

            List<KiteInstChange> instChangeList = querySceneInstService.listInstChanges(context.getSceneInstId(), InstType.OFFER_INST_ACCT);
            for (KiteInstChange instChange : instChangeList) {
                if (KiteStringUtils.isEqual(instChange.getInstId(), offerInst.getOfferInstId())
                    && KiteStringUtils.isEqual(instChange.getNewValue(), ActionType.D.name())
                    && !KiteStringUtils.isEqual(instChange.getOldValue(), ActionType.A.name())) {

                    List<KiteOfferInstAcct> delOfferInstAccts = querySceneInstService.listInsts(context.getSceneInstId(), Collections.singletonList(InstType.OFFER_INST_ACCT));
                 // 删除的付费关系
                    delOfferInstAccts.forEach((acctRel) -> {
                        if (KiteStringUtils.isEqual(ActionType.D.name(), acctRel.getActionType().name())
                            && KiteStringUtils.isEqual(instChange.getSubInstId(), acctRel.getInstId())
                            && isExist(accounts,acctRel)) {
                            String bssId = "";
                            String cBssId = "";
                            if (!KiteObjectUtils.isEmpty(kitePosDTO)) {
                                String accountCustId = acctRel.getCustId();
                                if (KiteStringUtils.equals(custId, accountCustId)) {
                                    bssId = context.getCustDto().getCustId();
                                    cBssId = context.getCustDto().getProvinceCustId();
                                }
                                else {
                                    CuccCustInfoDetailDTO custInfoDetailDTO = getCust(accountCustId, custMap);
                                    if (Objects.nonNull(custInfoDetailDTO)) {
                                        bssId = custInfoDetailDTO.getCustId();
                                        cBssId = custInfoDetailDTO.getProvinceCustId();
                                    }
                                }
                            }
                            KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
                            KitePosAccountDTO account = new KitePosAccountDTO();
                            account.setInstanceId(acctRel.getInstId());
                            if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(kiteSceneInst.getServiceOfferId())
                                    && KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(context.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
                                account.setInstanceId(CommonUtil.getInstanceId(LocalKeyConsts.ZH_INST_CODE, acctRel.getInstId()));
                            }
                            account.setCustId(acctRel.getCustId());
                            account.setAccountId(acctRel.getAcctId());
                            account.setName(acctRel.getAcctName());
                            account.setPayMode(acctRel.getPayModeCode()); //账户类型
                            account.setProvinceCode(acctRel.getProvinceCode()); //省份-广东
                            account.setEparchyCode(acctRel.getEparchyCode()); //地市
                            account.setIsGroupAccount(acctRel.getIsDefault());
                            account.setChangeType(ChangeTypeUtils.getChangeType(acctRel.getActionType().name()));
                            //account.setOpenDate(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
                            if (!ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
                                account.setBssId(bssId);
                                account.setCbssId(cBssId);
                            }
                            else {
                                // 从缓存里面取
                                String sceneInstId = context.getSceneInstId();
                                List<InstAttrDTO> attrConfigs = queryScenePersonService
                                    .listKiteConfigAttrs(sceneInstId, LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE).getResultObject().stream()
                                    .filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType()))
                                    .collect(Collectors.toList());
                                Map<String, String> orderAttrMap = new HashMap<String, String>();
                                attrConfigs.forEach(orderAttr ->  orderAttrMap.put(orderAttr.getFieldName(), orderAttr.getValue()));
                                account.setBssId(orderAttrMap.get("provinceAcctId"));
                                account.setCbssId(orderAttrMap.get("cbssAcctId"));
                                account.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                                String isDefault = orderAttrMap.get("is_trans_acct");
                                if (KiteStringUtils.isEqual(isDefault, "1")) {
                                    account.setCustId("");
                                }
                                // 2021-12-22版本，过户，取消将默认账户转到新客户下的逻辑
                                /*else {

                                    Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
                                    Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
                                    CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ?
                                        (CuccCustInfoDTO) newCust :
                                        context.getNewCustDto();
                                    account.setCustId(newCustDto.getCustId());
                                }*/
                                account.setIsCenterDirectSign("0");
                                account.setAcctContractCode(orderAttrMap.get("acctContractCode"));

                            }
                            accounts.add(account);
                        }

                    });
                }
            }
            List<KitePosAccountDTO> dealAcctTransferDtos = dealPayRelationAccountingTransfer(context, offerInstAcctRels, accounts);
            KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
            String isDefaultAcct = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "isDefaultAcct");
            if (KiteListUtils.isNotEmpty(dealAcctTransferDtos) && ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())
                && KiteStringUtils.equals("1", isDefaultAcct)) {
                accounts.removeIf(account -> !account.getInstanceId().equals(dealAcctTransferDtos.get(0).getInstanceId()));
            }
        });
        context.getPosDto().setAccounts(accounts);
    }

    @SuppressWarnings("deprecation")
    private CuccCustInfoDTO queryNewCustInfo(String custId) {
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        kiteCustomerInfoReq.setCustId(custId);
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setPageNum(1);
        kiteCustomerInfoReq.setPageSize(10);
        // 调用查询客户列表
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQuery(kiteCustomerInfoReq);
        if (!KiteObjectUtils.isEmpty(list) && KiteListUtils.isNotEmpty(list.getList())) {
            List<CuccCustInfoDTO> cuccCustInfoDTOList = list.getList();
            cuccCustInfoDTO = cuccCustInfoDTOList.get(0);
        }
        return cuccCustInfoDTO;
    }

    private boolean isExist(List<KitePosAccountDTO> accounts, KiteOfferInstAcct acctRel) {
        String accountId = acctRel.getAcctId();
        for (KitePosAccountDTO account : accounts) {
            if (KiteStringUtils.isEqual(account.getAccountId(), accountId)) {
                account.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                return false;
            }
        }
        return true;
    }

    private CuccCustInfoDetailDTO getCust(String accountCustId, Map<String, Object> custMap) {
        CuccCustInfoDetailDTO custInfoDetailDTO = (CuccCustInfoDetailDTO) custMap.get(accountCustId);
        if (Objects.isNull(custInfoDetailDTO) && KiteStringUtils.isNotEmpty(accountCustId)) {
            custInfoDetailDTO = custReceptionService.getCustomerInfoNew(accountCustId);
            custMap.put(accountCustId, custInfoDetailDTO);
        }
        return custInfoDetailDTO;
    }

    // 过户 有两条及以上账户关系时特殊处理
    private List<KitePosAccountDTO> dealPayRelationAccountingTransfer(KitePosHandlerContext context, List<KiteOfferInstAcct> offerInstAcctRels, List<KitePosAccountDTO> accounts) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        if (!ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
            return accounts;
        }
        String isDefaultAcct = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "isDefaultAcct");
        // 过户选择过默认账户且默认账户有多条时进行特殊处理
        if (KiteStringUtils.equals("1", isDefaultAcct) && offerInstAcctRels.size() > 1) {
            // 只处理有默认付费关系的数据
            offerInstAcctRels = offerInstAcctRels.stream().filter(offerInstAcctRel -> "1".equals(offerInstAcctRel.getIsDefault())
                && ActionType.K.equals(offerInstAcctRel.getActionType())).collect(Collectors.toList());
            List<KiteOfferInstAcct> tmpOfferInstAcctRels = new ArrayList<>();
            for (KiteOfferInstAcct offerInstAcctRel : offerInstAcctRels) {
                // 获取当前付费关系的起始账期
                String subStartDate = offerInstAcctRel.getStartDate();
                // 获取当前年月
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MONTH, 1);
                SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
                String nextMonth = dft.format(cal.getTime());
                // 只过次月生效的默认账户
                if (KiteStringUtils.equals(subStartDate, nextMonth) && KiteStringUtils.equals("1", offerInstAcctRel.getIsDefault())) {
                    tmpOfferInstAcctRels.add(offerInstAcctRel);
                }
            }
            if (KiteListUtils.isNotEmpty(tmpOfferInstAcctRels)) {
                offerInstAcctRels = tmpOfferInstAcctRels;

            }
            // 存在多条次月生效的默认账户或多条默认账户 只取一条账户传下去
            if (offerInstAcctRels.size() >= 1) {
                String acctRelInstId = offerInstAcctRels.get(0).getInstId();
                return accounts.stream().filter(account -> KiteStringUtils.equals(account.getInstanceId().substring(2), acctRelInstId)).collect(Collectors.toList());
            }
        }
        return accounts;
    }
}
